<template>
  <div>
    <div class="gui-padding bg" style="border-bottom: 1px solid #eee;" >
      <a-breadcrumb>
        <a-breadcrumb-item>公司管理</a-breadcrumb-item>
        <a-breadcrumb-item>公司用户</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="gui-padding  flex justify-content-between flex-wrap" style="padding-top: 0;padding-bottom: 0">
      <div style="width: 240px;height: calc(100vh - 115px);overflow: auto;border-right: 1px solid #eee;padding:10px 10px;">
          <h1 @click.prevent="handleSearchAll" class="fz14 pointer">{{companyList.name}}</h1>
          <a-tree v-model:selectedKeys="selectedKeys" :tree-data="companyList.children"
                  :field-names="{title:'name'}"
                  show-icon default-expand-all @select="handleSelectNode">

            <template #title="data">
              <span >{{ data.name }}</span><span class="ml5">({{data.count || 0}} 人)</span>
            </template>

            <template #switcherIcon="{ switcherCls }"><down-outlined :class="switcherCls" /></template>
            <template #icon="{ key, selected }">
              <template v-if="key === '0-0'">
                <MinusSquareOutlined />
              </template>
              <template v-else-if="key === '0-0-0'">
                <MinusSquareOutlined />
              </template>
              <template v-else>
                <MinusSquareOutlined  v-if="selected" />
                <FolderOutlined  v-else />
              </template>
            </template>
          </a-tree>
        </div>
      <div  style="width: calc(100% - 260px);" class="mt10">
        <div class="flex justify-content-between mb10">
          <div class="flex">
            <div>
              <span class="mr5"><a-button type="primary" size="small"  @click="handleAddOpen"> <template
                  #icon><PlusOutlined/> </template>添加</a-button></span>
              <span class="mr5"><a-button type="primary" danger size="small" @click="handleOpenRecycle">
            <DeleteOutlined/>
            回收站
          </a-button></span>
            </div>
          </div>
          <div>
            <a-form layout="inline" autocomplete="off" ref="searchFormRef" :model="queryParams">
              <a-form-item label="搜索关键词" name="keyword">
                <a-input v-model:value.trim="queryParams.keyword" size="small" style="width: 190px"
                         placeholder="请输入用户名/姓名/手机" allow-clear/>
              </a-form-item>
              <a-form-item label="状态" name="status">
                <a-select
                    ref="select"
                    size="small"
                    placeholder="请选择"
                    allow-clear
                    v-model:value="queryParams.status"
                    style="width: 120px"
                >
                  <a-select-option :value="1">激活</a-select-option>
                  <a-select-option :value="0">未激活</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <div class="flex">
                  <a-button type="primary" size="small" @click="handleSearch">
                    <SearchOutlined/>
                    搜索
                  </a-button>
                  <a-button type="primary" danger size="small" @click="handleReset" class="ml10">
                    <UndoOutlined/>
                    重置
                  </a-button>
                </div>
              </a-form-item>
            </a-form>
          </div>
        </div>
        <a-table
            :columns="columns"
            rowClassName="items"
            :loading="tableLoading"
            rowKey="id"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
            :pagination="false"
            :data-source="tableData"
            style="height:calc(100vh - 235px)"
            size="small" sticky bordered>
          <template #bodyCell="{ column,text,record,index }">
<!--            <template v-if="column.dataIndex==='username'">
              <div class="flex">
                <img :src="record.avatar" class="avatar" style="width: 24px;height: 24px;border-radius: 50%;">
                <span class="ml10">{{ record.username }}</span>
              </div>
            </template>-->
            <template v-if="column.dataIndex==='status'">
              <a-switch v-model:checked="record.status" @change="handleChangeUpdate(record,'status')"

                        :checked-value="1"
                        :un-checked-value="0"
                        checked-children="激活中"
                        un-checked-children="未激活"/>
            </template>
            <template v-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                 <span class="mr5">
                  <a-button type="primary"  size="small" @click="handleEditOpen(record)"> <template
                      #icon><EditOutlined style="font-size:12px"/></template>编辑</a-button>
                </span>
                <span class="mr5">
                  <a-button type="primary"  class="mainbg2" @click="handleUpdatePassword(record)"
                            size="small"> <template #icon><EditOutlined
                      style="font-size:12px"/></template>重置密码</a-button>
                </span>
                <a-popconfirm title="你确定删除吗?"  @confirm="handleDelete(record.id)">
                  <a-button type="primary"  size="small" danger>
                    <template #icon>
                      <CloseOutlined
                          style="font-size:12px"/>
                    </template>
                    删除
                  </a-button>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
        <div class="flex  mt20">
        <a-pagination
            v-model:current="queryParams.pageNo"
            v-model:page-size="queryParams.pageSize"
            @change="handleChangePageNo"
            :page-size-options="pageSizeOptions"
            :show-total="total => `共 ${total} 项`"
            show-size-changer
            :total="total"/>
      </div>
      </div>
    </div>
    <add-user ref="addOpenRef" @success="handleLoadData"></add-user>
    <user-password ref="passwordRef"></user-password>
    <user-recycle ref="recycleRef" @success="handleLoadData"></user-recycle>
  </div>
</template>
<script setup>
import AddUser from "../rbac/compoments/AddUser.vue";
import UserPassword from "../rbac/compoments/UserPassword.vue";
import UserRecycle from "../rbac/compoments/UserRecycle.vue";

const recycleRef = ref(null)
const companyList = ref([])
const passwordRef = ref(null)
const addOpenRef = ref(null)
const searchFormRef = ref(null)
const tableLoading = ref(false)
const total = ref(0)
const tableData = ref([]);
const pageSizeOptions = ref(['15', '20', '30', '40', '50']);
const queryParams = reactive({
  pageNo: 1,
  pageSize: 15,
  status: null,
  departmentId:"",
  keyword: ''
})

// 控制表格checkbox选中
const state = reactive({
  selectedRowKeys: [],
  loading: false,
})

const columns = [
  {title: '用户名', width: 150, dataIndex: 'account', align: "center"},
  {title: '姓名', width: 150, dataIndex: 'username', align: "center"},
  {title: '手机', width: 150, dataIndex: 'phone', align: "center"},
  {title: '船舶', width: 200, dataIndex: 'chuanboNames', align: "center",ellipsis: true},
  {title: '船员分组', width: 200, dataIndex: 'groupNames', align: "center",ellipsis: true},
  {title: '角色', width: 150, dataIndex: 'roleNames', align: "center",ellipsis: true},
  {title: '状态', width: 100, dataIndex: 'status', align: "center"},
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    align: "center",
    width: 280,
  },
];

const handleCompanyList = async ()=>{
  try {
    const resp = await useGetAdminCurrentSystemApi(queryParams)
    companyList.value = resp.data
  } catch (e) {
  }
}

const handleSelectNode = (selectKeys,e) => {
  queryParams.pageNo = 0
  queryParams.departmentId = e.node.id
  handleLoadData()
}

/**
 * 查询列表数据
 */
const handleLoadData = async () => {
  try {
    tableLoading.value = true
    const resp = await useFindUserListBySystemIdApi(queryParams)
    tableLoading.value = false
    tableData.value = resp.data.records
    total.value = resp.data.total
  } catch (e) {
    useMessage().error(e.msg)
  }
}

// 改变分页查询
const handleChangePageNo = (pno, psize) => {
  queryParams.pageNo = pno;
  queryParams.pageSize = psize;
  handleLoadData()
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1;
  handleLoadData()
}

// 搜索
const handleSearchAll = () => {
  queryParams.departmentId = ""
  queryParams.pageNo = 1;
  handleLoadData()
}

const handleReset = () => {
  searchFormRef.value.resetFields()
  handleLoadData()
}

// 修改状态
const handleChangeUpdate = async (record, field) => {
  await useHandleUpdateStatusUserApi({id: record.id, field: field, value: record[field]})
  useMessage().success("操作成功!")
}

// 选择行
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys
};

/**
 * 删除逻辑
 * @param id
 * @returns {Promise<void>}
 */
const handleDelete = async (id) => {
  try {
    await useDelUserApi(id)
    notification.destroy()
    notification.success({
      "message": "提示",
      "description": "删除成功"
    })
    handleLoadData()
  }catch (e){
    useMessage().error(e.msg)
  }
}

// 打开回收站modal
const handleOpenRecycle = () => {
  recycleRef.value.handleOpen()
}

// 打开添加
const handleAddOpen = () => {
  addOpenRef.value.handleAddOpen()
}

// 编辑处理
const handleEditOpen = (record) => {
  addOpenRef.value.handleAddOpen({...record})
}


// 打开重置密码modal
const handleUpdatePassword = (record) => {
  passwordRef.value.handleOpen(record)
}

// 批量处理-删除
const handleBatchDel = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchDelsApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}
// 批量处理-激活
const handleBatchStatus = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchStatusApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}
// 批量处理-禁止
const handleBatchForbidden = async () => {
  var keys = [...state.selectedRowKeys]
  await useBatchForbiddensApi({ids: keys})
  state.selectedRowKeys = []
  handleLoadData();
}

onMounted(() => {
  handleCompanyList()
  handleLoadData()
})

</script>

